import socket
import threading


class WebServer:
    not_found_msg = """<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
    <html><head>
    <title>404 Not Found</title>
    </head><body>
    <h1>Not Found</h1>
    <p>The requested URL {path} was not found on this server.</p>
    </body></html>"""

    def __init__(self, host='', port=80):
        # 创建TCP服务端socket
        self.tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # 设置端口号复用，程序退出端口立即释放
        self.tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
        # 绑定端口号
        self.tcp_server_socket.bind((host, port))
        # 设置监听
        self.tcp_server_socket.listen(128)

    def handle_client_request(self, conn_socket):
        """处理客户端请求"""
        # 2.获取浏览器发送的HTTP请求报文数据
        client_request_data = conn_socket.recv(4096).decode()
        print(client_request_data)

        if not client_request_data:
            conn_socket.close()
            return

        # 3.获取用户请求资源的路径
        path = client_request_data.splitlines()[0].split()[1]
        if path == '/':
            path = '/index.html'

        try:
            # 4.根据请求资源的路径，读取指定文件的数据
            with open('static' + path, 'rb') as f:
                file_data = f.read()
        except FileNotFoundError:  # 5.判断请求的文件在服务端不存在
            # 组装404状态的响应报文，发送给浏览器
            response_line = "HTTP/1.1 404 Not Found\r\n"
            response_header = "Server: Python Web\r\n"
            response_body = self.not_found_msg.format(path=path)
            response_data = (response_line + response_header + '\r\n' + response_body).encode()
            conn_socket.send(response_data)
        else:
            # 响应行
            response_line = "HTTP/1.1 200 OK\r\n"
            # 响应头
            response_header = "Server: Python Web\r\n"
            # 响应体
            response_body = file_data
            # 组装HTTP格式的响应报文
            response_data = (response_line + response_header + '\r\n').encode() + response_body
            conn_socket.send(response_data)
        finally:
            # 6.HTTP响应报文数据发送完成后，关闭服务于客户端的套接字
            conn_socket.close()

    def start(self):
        """开启Web服务器"""
        # 循环接收客户端的连接请求
        while True:
            # 等待接收客户端的连接请求
            conn_client_socket, ip_port = self.tcp_server_socket.accept()
            # 连接建立成功，开辟子线程处理客户端请求
            t = threading.Thread(target=self.handle_client_request, args=(conn_client_socket,))
            t.start()


if __name__ == '__main__':
    WebServer().start()
